﻿using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DjangoRESTFrameworkDAL.REST
{
    public interface IPost<T>
    {
        string Url { get; }
    }

    public static class PostEx
    {
        /// <summary>
        ///     创建或更新对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dal">DAL实例化对象</param>
        /// <param name="entity">待创建或更新对象</param>
        /// <returns>创建的对象</returns>
        public static async Task<T> PostAsync<T>(this IPost<T> dal, T entity)
        {
            var content = new StringContent(JsonConvert.SerializeObject(entity));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await RestHttpClient.Instance.PostWithPolicyAsync(dal.Url, content);
            var responseBody = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(responseBody);
        }
    }
}